<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    别用Date了，Java8新特性之日期处理，现在学会也不迟.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-develop/别用Date了，Java8新特性之日期处理，现在学会也不迟"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  别用Date了，Java8新特性之日期处理，现在学会也不迟.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/develop/%E5%88%AB%E7%94%A8Date%E4%BA%86%EF%BC%8CJava8%E6%96%B0%E7%89%B9%E6%80%A7%E4%B9%8B%E6%97%A5%E6%9C%9F%E5%A4%84%E7%90%86%EF%BC%8C%E7%8E%B0%E5%9C%A8%E5%AD%A6%E4%BC%9A%E4%B9%9F%E4%B8%8D%E8%BF%9F/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/develop/">develop</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">4.4k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">19 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="别用Date了，Java8新特性之日期处理，现在学会也不迟"><a href="#别用Date了，Java8新特性之日期处理，现在学会也不迟" class="headerlink" title="别用Date了，Java8新特性之日期处理，现在学会也不迟"></a>别用Date了，Java8新特性之日期处理，现在学会也不迟</h1><p>前天小Hub发了一篇《<a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzIwODkzOTc1MQ==&mid=2247484420&idx=1&sn=8e7ce445a95a6121e40d7931dbdc98c4&chksm=977a3b8ca00db29a12cf7a0c205a4eac49ae65bd341c5e48fb26a7399a3966b06d1ac2152fc6&scene=21#wechat_redirect">SpringBoot 全局日期格式化（基于注解）</a>》文章，很多读者都指出了文中几个不严谨的地方，其中关于实体类中使用Date类型线程不安全。在JDK8中我们已经开始使用LocalDateTime，那么对于这个类的用法，如果有同学不了解的话，来看看下面的文章，小Hub看了一遍，觉得作者写得很详细了，对比式写法，更加通俗易懂！</p>
<p>看完别忘了在文末右下角点个[在看]赞一赞噢~</p>
<hr>
<blockquote>
<p>作者：WayfreemBlog</p>
<p>来源：segmentfault.com/a/1190000012922933</p>
</blockquote>
<h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p>伴随 <code>lambda表达式</code>、 <code>streams</code> 以及一系列小优化，Java 8 推出了全新的日期时间API。</p>
<p>Java处理日期、日历和时间的不足之处：将 java.util.Date 设定为可变类型，以及 SimpleDateFormat 的非线程安全使其应用非常受限。然后就在 java8 上面增加新的特性。</p>
<p>全新API的众多好处之一就是，明确了日期时间概念，例如： <code>瞬时（instant）</code>、 <code>长短（duration）</code>、 <code>日期</code>、 <code>时间</code>、 <code>时区</code>和 <code>周期</code>。</p>
<p>同时继承了Joda 库按人类语言和计算机各自解析的时间处理方式。不同于老版本，新API基于ISO标准日历系统，java.time包下的所有类都是不可变类型而且线程安全。</p>
<h3 id="关键类"><a href="#关键类" class="headerlink" title="关键类"></a>关键类</h3><ul>
<li>Instant：瞬时实例。</li>
<li>LocalDate：本地日期，不包含具体时间 例如：2014-01-14 可以用来记录生日、纪念日、加盟日等。</li>
<li>LocalTime：本地时间，不包含日期。</li>
<li>LocalDateTime：组合了日期和时间，但不包含时差和时区信息。</li>
<li>ZonedDateTime：最完整的日期时间，包含时区和相对UTC或格林威治的时差。</li>
</ul>
<p>新API还引入了 ZoneOffSet 和 ZoneId 类，使得解决时区问题更为简便。解析、格式化时间的 DateTimeFormatter 类也全部重新设计。</p>
<h3 id="实战"><a href="#实战" class="headerlink" title="实战"></a>实战</h3><p>在教程中我们将通过一些简单的实例来学习如何使用新API，因为只有在实际的项目中用到，才是学习新知识以及新技术最快的方式。</p>
<h3 id="1-获取当前的日期"><a href="#1-获取当前的日期" class="headerlink" title="1. 获取当前的日期"></a>1. 获取当前的日期</h3><p>Java 8 中的 <code>LocalDate</code> 用于表示当天日期。和 java.util.Date不同，它只有日期，不包含时间。当你仅需要表示日期时就用这个类。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;获取今天的日期public void getCurrentDate()&#123;    LocalDate today &#x3D; LocalDate.now();    System.out.println(&quot;Today&#39;s Local date : &quot; + today);</span><br><span class="line">    &#x2F;&#x2F;这个是作为对比    Date date &#x3D; new Date();    System.out.println(date);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541141.webp" alt="clipboard.png"></p>
<p>上面的代码创建了当天的日期，不含时间信息。打印出的日期格式非常友好，不像 Date类 打印出一堆没有格式化的信息。</p>
<h3 id="2-获取年、月、日信息"><a href="#2-获取年、月、日信息" class="headerlink" title="2. 获取年、月、日信息"></a>2. 获取年、月、日信息</h3><p><code>LocalDate</code> 提供了获取年、月、日的快捷方法，其实例还包含很多其它的日期属性。通过调用这些方法就可以很方便的得到需要的日期信息，不用像以前一样需要依赖java.util.Calendar类了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;获取年、月、日信息public void getDetailDate()&#123;    LocalDate today &#x3D; LocalDate.now();    int year &#x3D; today.getYear();    int month &#x3D; today.getMonthValue();    int day &#x3D; today.getDayOfMonth();</span><br><span class="line">    System.out.printf(&quot;Year : %d  Month : %d  day : %d t %n&quot;, year, month, day);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167544945.webp" alt="clipboard.png"></p>
<h3 id="3-处理特定日期"><a href="#3-处理特定日期" class="headerlink" title="3.处理特定日期"></a>3.处理特定日期</h3><p>在第一个例子里，我们通过静态工厂方法now()非常容易地创建了当天日期。</p>
<p>我们还可以调用另一个有用的工厂方法 <code>LocalDate.of()</code> 创建任意日期， 该方法需要传入年、月、日做参数，返回对应的LocalDate实例。这个方法的好处是没再犯老API的设计错误，比如年度起始于1900，月份是从 <code>0</code> 开始等等。日期所见即所得，就像下面这个例子表示了1月21日，直接明了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;处理特定日期public void handleSpecilDate()&#123;    LocalDate dateOfBirth &#x3D; LocalDate.of(2018, 01, 21);    System.out.println(&quot;The specil date is : &quot; + dateOfBirth);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541136.webp" alt="clipboard.png"></p>
<h3 id="4-判断两个日期是否相等"><a href="#4-判断两个日期是否相等" class="headerlink" title="4.判断两个日期是否相等"></a>4.判断两个日期是否相等</h3><p>现实生活中有一类时间处理就是判断两个日期是否相等。在项目开发的时候总会遇到这样子的问题。</p>
<p>下面这个例子会帮助你用Java 8的方式去解决， <code>LocalDate</code> 重载了equal方法。</p>
<p>注意，如果比较的日期是字符型的，需要先解析成日期对象再作判断。</p>
<p>请看下面的例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;判断两个日期是否相等public void compareDate()&#123;    LocalDate today &#x3D; LocalDate.now();    LocalDate date1 &#x3D; LocalDate.of(2018, 01, 21);</span><br><span class="line">    if(date1.equals(today))&#123;           System.out.printf(&quot;TODAY %s and DATE1 %s are same date %n&quot;, today, date1);    &#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541138.webp" alt="clipboard.png"></p>
<h3 id="5-检查像生日这种周期性事件"><a href="#5-检查像生日这种周期性事件" class="headerlink" title="5.检查像生日这种周期性事件"></a>5.检查像生日这种周期性事件</h3><p>Java 中另一个日期时间的处理就是检查类似生日、纪念日、法定假日（国庆以及春节）、或者每个月固定时间发送邮件给客户 这些周期性事件。</p>
<p>Java中如何检查这些节日或其它周期性事件呢？答案就是 <code>MonthDay</code>类。这个类组合了月份和日，去掉了年，这意味着你可以用它判断每年都会发生事件。</p>
<p>和这个类相似的还有一个 <code>YearMonth</code>类。这些类也都是不可变并且线程安全的值类型。下面我们通过 <code>MonthDay</code>来检查周期性事件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;处理周期性的日期public void cycleDate()&#123;    LocalDate today &#x3D; LocalDate.now();    LocalDate dateOfBirth &#x3D; LocalDate.of(2018, 01, 21);</span><br><span class="line">    MonthDay birthday &#x3D; MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());    MonthDay currentMonthDay &#x3D; MonthDay.from(today);</span><br><span class="line">    if(currentMonthDay.equals(birthday))&#123;       System.out.println(&quot;Many Many happy returns of the day !!&quot;);    &#125;else&#123;       System.out.println(&quot;Sorry, today is not your birthday&quot;);    &#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167544847.webp" alt="clipboard.png"></p>
<h3 id="6-获取当前时间"><a href="#6-获取当前时间" class="headerlink" title="6.获取当前时间"></a>6.获取当前时间</h3><p>与 获取日期 例子很像，获取时间使用的是 <code>LocalTime</code> 类，一个只有时间没有日期的LocalDate近亲。可以调用静态工厂方法now()来获取当前时间。默认的格式是 <code>hh:mm:ss:nnn</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;获取当前时间public void getCurrentTime()&#123;    LocalTime time &#x3D; LocalTime.now();    System.out.println(&quot;local time now : &quot; + time);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167544782.webp" alt="clipboard.png"></p>
<h3 id="7-在现有的时间上增加小时"><a href="#7-在现有的时间上增加小时" class="headerlink" title="7.在现有的时间上增加小时"></a>7.在现有的时间上增加小时</h3><p>Java 8 提供了更好的 plusHours() 方法替换 add() ，并且是兼容的。注意，这些方法返回一个全新的LocalTime实例，由于其不可变性，返回后一定要用变量赋值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;增加小时public void plusHours()&#123;    LocalTime time &#x3D; LocalTime.now();    LocalTime newTime &#x3D; time.plusHours(2); &#x2F;&#x2F; 增加两小时    System.out.println(&quot;Time after 2 hours : &quot; +  newTime);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541140.webp" alt="clipboard.png"></p>
<p><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s?__biz=MzI4OTA3NDQ0Nw==&mid=2455548022&idx=1&sn=572e8a1ebe18e9f012d99880bc977da6&scene=21#wechat_redirect">分享一套SpringBoot开发博客系统源码，以及完整开发文档！速度保存！</a></p>
<h3 id="8-如何计算一个星期之后的日期"><a href="#8-如何计算一个星期之后的日期" class="headerlink" title="8.如何计算一个星期之后的日期"></a>8.如何计算一个星期之后的日期</h3><p>和上个例子计算两小时以后的时间类似，这个例子会计算一周后的日期。LocalDate日期不包含时间信息，它的plus()方法用来增加天、周、月，ChronoUnit类声明了这些时间单位。由于LocalDate也是不变类型，返回后一定要用变量赋值。</p>
<p>可以用同样的方法增加1个月、1年、1小时、1分钟甚至一个世纪，更多选项可以查看Java 8 API中的ChronoUnit类。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;如何计算一周后的日期public void nextWeek()&#123;    LocalDate today &#x3D; LocalDate.now();    LocalDate nextWeek &#x3D; today.plus(1, ChronoUnit.WEEKS);    &#x2F;&#x2F;使用变量赋值    System.out.println(&quot;Today is : &quot; + today);    System.out.println(&quot;Date after 1 week : &quot; + nextWeek);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601366701101.webp" alt="clipboard.png"></p>
<h3 id="9-计算一年前或一年后的日期"><a href="#9-计算一年前或一年后的日期" class="headerlink" title="9.计算一年前或一年后的日期"></a>9.计算一年前或一年后的日期</h3><p>接着上面的例子中我们通过 <code>LocalDate</code> 的 <code>plus()</code> 方法增加天数、周数或月数，这个例子我们利用 <code>minus()</code> 方法计算一年前的日期。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;计算一年前或一年后的日期public void minusDate()&#123;    LocalDate today &#x3D; LocalDate.now();    LocalDate previousYear &#x3D; today.minus(1, ChronoUnit.YEARS);    System.out.println(&quot;Date before 1 year : &quot; + previousYear);</span><br><span class="line">    LocalDate nextYear &#x3D; today.plus(1, ChronoUnit.YEARS);    System.out.println(&quot;Date after 1 year : &quot; + nextYear);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541143.webp" alt="clipboard.png"></p>
<h3 id="10-使用Java-8的Clock时钟类"><a href="#10-使用Java-8的Clock时钟类" class="headerlink" title="10.使用Java 8的Clock时钟类"></a>10.使用Java 8的Clock时钟类</h3><p>Java 8增加了一个 Clock 时钟类用于获取当时的时间戳，或当前时区下的日期时间信息。以前用到System.currentTimeInMillis() 和 TimeZone.getDefault() 的地方都可用Clock替换。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">public void clock()&#123;    &#x2F;&#x2F; 根据系统时间返回当前时间并设置为UTC。    Clock clock &#x3D; Clock.systemUTC();    System.out.println(&quot;Clock : &quot; + clock);</span><br><span class="line">    &#x2F;&#x2F; 根据系统时钟区域返回时间    Clock defaultClock &#x3D; Clock.systemDefaultZone();    System.out.println(&quot;Clock : &quot; + clock);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541210.webp" alt="clipboard.png"></p>
<h3 id="11-判断日期是早于还是晚于另一个日期"><a href="#11-判断日期是早于还是晚于另一个日期" class="headerlink" title="11.判断日期是早于还是晚于另一个日期"></a>11.判断日期是早于还是晚于另一个日期</h3><p>LocalDate 类有两类方法 <code>isBefore()</code> 和 <code>isAfter()</code> 用于比较日期。调用 <code>isBefore()</code> 方法时，如果给定日期小于当前日期则返回 true。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;如何用Java判断日期是早于还是晚于另一个日期public void isBeforeOrIsAfter()&#123;    LocalDate today &#x3D; LocalDate.now();</span><br><span class="line">    LocalDate tomorrow &#x3D; LocalDate.of(2018, 1, 29);    if(tomorrow.isAfter(today))&#123;        System.out.println(&quot;Tomorrow comes after today&quot;);    &#125;</span><br><span class="line">    &#x2F;&#x2F;减去一天    LocalDate yesterday &#x3D; today.minus(1, ChronoUnit.DAYS);</span><br><span class="line">    if(yesterday.isBefore(today))&#123;        System.out.println(&quot;Yesterday is day before today&quot;);    &#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541137.webp" alt="clipboard.png"></p>
<h3 id="12-处理时区"><a href="#12-处理时区" class="headerlink" title="12.处理时区"></a>12.处理时区</h3><p>Java 8不仅分离了日期和时间，也把时区分离出来了。现在有一系列单独的类如 ZoneId 来处理特定时区，ZoneDateTime 类来表示某时区下的时间。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;获取特定时区下面的时间public void getZoneTime()&#123;    &#x2F;&#x2F;设置时区    ZoneId america &#x3D; ZoneId.of(&quot;America&#x2F;New_York&quot;);</span><br><span class="line">    LocalDateTime localtDateAndTime &#x3D; LocalDateTime.now();</span><br><span class="line">    ZonedDateTime dateAndTimeInNewYork  &#x3D; ZonedDateTime.of(localtDateAndTime, america );    System.out.println(&quot;现在的日期和时间在特定的时区 : &quot; + dateAndTimeInNewYork);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167548750.webp" alt="clipboard.png"></p>
<h3 id="13-如何体现出固定日期"><a href="#13-如何体现出固定日期" class="headerlink" title="13.如何体现出固定日期"></a>13.如何体现出固定日期</h3><p>例如：表示信用卡到期这类固定日期。与 MonthDay 检查重复事件的例子相似， <code>YearMonth</code> 是另一个组合类，用于表示信用卡到期日、FD到期日、期货期权到期日等。</p>
<p>还可以用这个类得到 当月共有多少天，YearMonth 实例的 <code>lengthOfMonth()</code> 方法可以返回当月的天数，在判断2月有28天还是29天时非常有用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;使用 YearMonth类处理特定的日期public void checkCardExpiry()&#123;    YearMonth currentYearMonth &#x3D; YearMonth.now();    System.out.printf(&quot;Days in month year %s: %d%n&quot;, currentYearMonth, currentYearMonth.lengthOfMonth());</span><br><span class="line">    YearMonth creditCardExpiry &#x3D; YearMonth.of(2028, Month.FEBRUARY);    System.out.printf(&quot;Your credit card expires on %s %n&quot;, creditCardExpiry);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541039.webp" alt="clipboard.png"></p>
<h3 id="14-检查闰年"><a href="#14-检查闰年" class="headerlink" title="14.检查闰年"></a>14.检查闰年</h3><p>LocalDate类有一个很实用的方法 <code>isLeapYear()</code> 判断该实例是否是一个闰年，如果你还是想重新发明轮子，这有一个代码示例，纯Java逻辑编写的判断闰年的程序。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;检查闰年public void isLeapYear()&#123;    LocalDate today &#x3D; LocalDate.now();    if(today.isLeapYear())&#123;        System.out.println(&quot;This year is Leap year&quot;);    &#125;else &#123;        System.out.println(&quot;2018 is not a Leap year&quot;);    &#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541204.webp" alt="clipboard.png"></p>
<h3 id="15-计算两个日期之间的天数和月数"><a href="#15-计算两个日期之间的天数和月数" class="headerlink" title="15.计算两个日期之间的天数和月数"></a>15.计算两个日期之间的天数和月数</h3><p>有一个常见日期操作是计算两个日期之间的天数、周数或月数。在Java 8中可以用java.time.Period类来做计算。下面这个例子中，我们计算了当天和将来某一天之间的月数。</p>
<p>下面的例子：现在是一月份，距离到五月份，中间相隔3月</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;计算两个日期之间的天数和月数public void calcDateDays()&#123;    LocalDate today &#x3D; LocalDate.now();</span><br><span class="line">    LocalDate java8Release &#x3D; LocalDate.of(2018, Month.MAY, 14);</span><br><span class="line">    Period periodToNextJavaRelease &#x3D; Period.between(today, java8Release);</span><br><span class="line">    System.out.println(&quot;Months left between today and Java 8 release : &quot;                                           + periodToNextJavaRelease.getMonths() );&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541139.png" alt="clipboard.png"></p>
<h3 id="16-包含时差信息的日期和时间"><a href="#16-包含时差信息的日期和时间" class="headerlink" title="16.包含时差信息的日期和时间"></a>16.包含时差信息的日期和时间</h3><p>ZoneOffset类用来表示时区，举例来说印度与GMT或UTC标准时区相差+05:30，可以通过ZoneOffset.of()静态方法来 获取对应的时区。一旦得到了时差就可以通过传入LocalDateTime和ZoneOffset来创建一个OffSetDateTime对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public void ZoneOffset()&#123;    LocalDateTime datetime &#x3D; LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30);    ZoneOffset offset &#x3D; ZoneOffset.of(&quot;+05:30&quot;);    OffsetDateTime date &#x3D; OffsetDateTime.of(datetime, offset);    System.out.println(&quot;Date and Time with timezone offset in Java : &quot; + date);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541135.png" alt="clipboard.png"></p>
<h3 id="17-获取当前的时间戳"><a href="#17-获取当前的时间戳" class="headerlink" title="17.获取当前的时间戳"></a>17.获取当前的时间戳</h3><p>Instant类有一个静态工厂方法now()会返回当前的时间戳，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public void getTimestamp()&#123;    Instant timestamp &#x3D; Instant.now();    System.out.println(&quot;What is value of this instant &quot; + timestamp);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541142.png" alt="clipboard.png"></p>
<h3 id="18-使用预定义的格式化工具去解析或格式化日期"><a href="#18-使用预定义的格式化工具去解析或格式化日期" class="headerlink" title="18.使用预定义的格式化工具去解析或格式化日期"></a>18.使用预定义的格式化工具去解析或格式化日期</h3><p>Java 8引入了全新的日期时间格式工具，线程安全而且使用方便。它自带了一些常用的内置格式化工具。</p>
<p>下面这个例子使用了BASICISODATE格式化工具将2018年2月10日格式化成20180210。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 使用预定义的格式化工具去解析或格式化日期public void formateDate()&#123;    String dayAfterTommorrow &#x3D; &quot;20180210&quot;;    LocalDate formatted &#x3D; LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);    System.out.printf(&quot;Date generated from String %s is %s %n&quot;, dayAfterTommorrow, formatted);&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://iubest.gitee.io/pic/640-1601167541218.webp" alt="clipboard.png"></p>
<h3 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h3><p>最后附上全部代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">package com.wq.study.java8.date;</span><br><span class="line">import java.time.Clock;import java.time.Instant;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.Month;import java.time.MonthDay;import java.time.OffsetDateTime;import java.time.ZoneOffset;import java.time.Period;import java.time.YearMonth;import java.time.ZoneId;import java.time.ZonedDateTime;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoUnit;import java.util.Date;</span><br><span class="line">public class DateTest &#123;</span><br><span class="line">    &#x2F;&#x2F;获取今天的日期    public void getCurrentDate()&#123;        LocalDate today &#x3D; LocalDate.now();        System.out.println(&quot;Today&#39;s Local date : &quot; + today);</span><br><span class="line">        &#x2F;&#x2F;这个是作为对比        Date date &#x3D; new Date();        System.out.println(date);    &#125;</span><br><span class="line">    &#x2F;&#x2F;获取年、月、日信息    public void getDetailDate()&#123;        LocalDate today &#x3D; LocalDate.now();        int year &#x3D; today.getYear();        int month &#x3D; today.getMonthValue();        int day &#x3D; today.getDayOfMonth();</span><br><span class="line">        System.out.printf(&quot;Year : %d  Month : %d  day : %d t %n&quot;, year, month, day);    &#125;</span><br><span class="line">    &#x2F;&#x2F;处理特定日期    public void handleSpecilDate()&#123;        LocalDate dateOfBirth &#x3D; LocalDate.of(2018, 01, 21);        System.out.println(&quot;The specil date is : &quot; + dateOfBirth);    &#125;</span><br><span class="line">    &#x2F;&#x2F;判断两个日期是否相等    public void compareDate()&#123;        LocalDate today &#x3D; LocalDate.now();        LocalDate date1 &#x3D; LocalDate.of(2018, 01, 21);</span><br><span class="line">        if(date1.equals(today))&#123;            System.out.printf(&quot;TODAY %s and DATE1 %s are same date %n&quot;, today, date1);        &#125;    &#125;</span><br><span class="line">    &#x2F;&#x2F;处理周期性的日期    public void cycleDate()&#123;        LocalDate today &#x3D; LocalDate.now();        LocalDate dateOfBirth &#x3D; LocalDate.of(2018, 01, 21);</span><br><span class="line">        MonthDay birthday &#x3D; MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());        MonthDay currentMonthDay &#x3D; MonthDay.from(today);</span><br><span class="line">        if(currentMonthDay.equals(birthday))&#123;           System.out.println(&quot;Many Many happy returns of the day !!&quot;);        &#125;else&#123;           System.out.println(&quot;Sorry, today is not your birthday&quot;);        &#125;    &#125;</span><br><span class="line">    &#x2F;&#x2F;获取当前时间    public void getCurrentTime()&#123;        LocalTime time &#x3D; LocalTime.now();        System.out.println(&quot;local time now : &quot; + time);    &#125;</span><br><span class="line">    &#x2F;&#x2F;增加小时    public void plusHours()&#123;        LocalTime time &#x3D; LocalTime.now();        LocalTime newTime &#x3D; time.plusHours(2); &#x2F;&#x2F; 增加两小时        System.out.println(&quot;Time after 2 hours : &quot; +  newTime);    &#125;</span><br><span class="line">    &#x2F;&#x2F;如何计算一周后的日期    public void nextWeek()&#123;        LocalDate today &#x3D; LocalDate.now();        LocalDate nextWeek &#x3D; today.plus(1, ChronoUnit.WEEKS);        System.out.println(&quot;Today is : &quot; + today);        System.out.println(&quot;Date after 1 week : &quot; + nextWeek);    &#125;</span><br><span class="line">    &#x2F;&#x2F;计算一年前或一年后的日期    public void minusDate()&#123;        LocalDate today &#x3D; LocalDate.now();        LocalDate previousYear &#x3D; today.minus(1, ChronoUnit.YEARS);        System.out.println(&quot;Date before 1 year : &quot; + previousYear);</span><br><span class="line">        LocalDate nextYear &#x3D; today.plus(1, ChronoUnit.YEARS);        System.out.println(&quot;Date after 1 year : &quot; + nextYear);    &#125;</span><br><span class="line">    public void clock()&#123;        &#x2F;&#x2F; 根据系统时间返回当前时间并设置为UTC。        Clock clock &#x3D; Clock.systemUTC();        System.out.println(&quot;Clock : &quot; + clock);</span><br><span class="line">        &#x2F;&#x2F; 根据系统时钟区域返回时间        Clock defaultClock &#x3D; Clock.systemDefaultZone();        System.out.println(&quot;Clock : &quot; + clock);    &#125;</span><br><span class="line">    &#x2F;&#x2F;如何用Java判断日期是早于还是晚于另一个日期    public void isBeforeOrIsAfter()&#123;        LocalDate today &#x3D; LocalDate.now();</span><br><span class="line">        LocalDate tomorrow &#x3D; LocalDate.of(2018, 1, 29);        if(tomorrow.isAfter(today))&#123;            System.out.println(&quot;Tomorrow comes after today&quot;);        &#125;</span><br><span class="line">        LocalDate yesterday &#x3D; today.minus(1, ChronoUnit.DAYS);</span><br><span class="line">        if(yesterday.isBefore(today))&#123;            System.out.println(&quot;Yesterday is day before today&quot;);        &#125;    &#125;</span><br><span class="line">    &#x2F;&#x2F;时区处理    public void getZoneTime()&#123;        &#x2F;&#x2F;设置时区        ZoneId america &#x3D; ZoneId.of(&quot;America&#x2F;New_York&quot;);</span><br><span class="line">        LocalDateTime localtDateAndTime &#x3D; LocalDateTime.now();</span><br><span class="line">        ZonedDateTime dateAndTimeInNewYork  &#x3D; ZonedDateTime.of(localtDateAndTime, america );        System.out.println(&quot;现在的日期和时间在特定的时区 : &quot; + dateAndTimeInNewYork);    &#125;</span><br><span class="line">    &#x2F;&#x2F;使用 YearMonth类处理特定的日期    public void checkCardExpiry()&#123;        YearMonth currentYearMonth &#x3D; YearMonth.now();        System.out.printf(&quot;Days in month year %s: %d%n&quot;, currentYearMonth, currentYearMonth.lengthOfMonth());</span><br><span class="line">        YearMonth creditCardExpiry &#x3D; YearMonth.of(2028, Month.FEBRUARY);        System.out.printf(&quot;Your credit card expires on %s %n&quot;, creditCardExpiry);    &#125;</span><br><span class="line">    &#x2F;&#x2F;检查闰年    public void isLeapYear()&#123;        LocalDate today &#x3D; LocalDate.now();        if(today.isLeapYear())&#123;           System.out.println(&quot;This year is Leap year&quot;);        &#125;else &#123;            System.out.println(&quot;2018 is not a Leap year&quot;);        &#125;    &#125;</span><br><span class="line">    &#x2F;&#x2F;计算两个日期之间的天数和月数    public void calcDateDays()&#123;        LocalDate today &#x3D; LocalDate.now();</span><br><span class="line">        LocalDate java8Release &#x3D; LocalDate.of(2018, Month.MAY, 14);</span><br><span class="line">        Period periodToNextJavaRelease &#x3D; Period.between(today, java8Release);</span><br><span class="line">        System.out.println(&quot;Months left between today and Java 8 release : &quot;                                           + periodToNextJavaRelease.getMonths() );    &#125;</span><br><span class="line">    &#x2F;&#x2F; 包含时差信息的日期和时间    public void ZoneOffset()&#123;        LocalDateTime datetime &#x3D; LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30);        ZoneOffset offset &#x3D; ZoneOffset.of(&quot;+05:30&quot;);        OffsetDateTime date &#x3D; OffsetDateTime.of(datetime, offset);        System.out.println(&quot;Date and Time with timezone offset in Java : &quot; + date);    &#125;</span><br><span class="line">    &#x2F;&#x2F; 获取时间戳    public void getTimestamp()&#123;        Instant timestamp &#x3D; Instant.now();        System.out.println(&quot;What is value of this instant &quot; + timestamp);    &#125;</span><br><span class="line">    &#x2F;&#x2F; 使用预定义的格式化工具去解析或格式化日期    public void formateDate()&#123;        String dayAfterTommorrow &#x3D; &quot;20180210&quot;;        LocalDate formatted &#x3D; LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);        System.out.printf(&quot;Date generated from String %s is %s %n&quot;, dayAfterTommorrow, formatted);    &#125;</span><br><span class="line">    public static void main(String[] args) &#123;        DateTest dt &#x3D; new DateTest();</span><br><span class="line">        dt.formateDate();    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>Java 8日期时间API的重点</p>
<p>1）提供了javax.time.ZoneId 获取时区。</p>
<p>2）提供了LocalDate和LocalTime类。</p>
<p>3）Java 8 的所有日期和时间API都是不可变类并且线程安全，而现有的Date和Calendar API中的java.util.Date和SimpleDateFormat是非线程安全的。</p>
<p>4）主包是 java.time,包含了表示日期、时间、时间间隔的一些类。里面有两个子包java.time.format用于格式化， java.time.temporal用于更底层的操作。</p>
<p>5）时区代表了地球上某个区域内普遍使用的标准时间。每个时区都有一个代号，格式通常由区域/城市构成（Asia/Tokyo），在加上与格林威治或 UTC的时差。例如：东京的时差是+09:00。</p>
<hr>
<p>（完）</p>
<p>*<strong>MarkerHub文章索引：</strong>（点击阅读原文直达）*</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">https:&#x2F;&#x2F;github.com&#x2F;MarkerHub&#x2F;JavaIndex</span><br></pre></td></tr></table></figure> 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/develop/%E5%88%AB%E7%94%A8Date%E4%BA%86%EF%BC%8CJava8%E6%96%B0%E7%89%B9%E6%80%A7%E4%B9%8B%E6%97%A5%E6%9C%9F%E5%A4%84%E7%90%86%EF%BC%8C%E7%8E%B0%E5%9C%A8%E5%AD%A6%E4%BC%9A%E4%B9%9F%E4%B8%8D%E8%BF%9F/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/develop/" rel="tag">develop</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/develop/Spring+Quartz%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Spring+Quartz定时任务.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/develop/%E6%8F%90%E9%AB%98%E7%94%9F%E4%BA%A7%E6%95%88%E7%8E%87%EF%BC%813%E4%B8%AA%E5%B8%B8%E7%94%A8%E7%9A%84%E5%BC%80%E6%BA%90%E5%B7%A5%E5%85%B7%E5%BA%93%E5%88%86%E4%BA%AB/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">提高生产效率！3个常用的开源工具库分享.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>